package com.rongshu.view.submitArticle.presenter;

import android.Manifest;
import android.app.Activity;
import android.content.Context;

import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.rongshu.api.FileUploadService;
import com.rongshu.api.RetorfitService;
import com.rongshu.utils.Common;
import com.rongshu.utils.UserInfoUtils;
import com.rongshu.view.base.BaseActivity;
import com.rongshu.view.base.mvp.BasePresenter;
import com.rongshu.view.base.mvp.INetBean;
import com.rongshu.view.submitArticle.bean.SubmitPostBody;
import com.rongshu.view.submitArticle.view.SubmitPostView;
import com.rongshu.view.userInfo.entity.UpLoadImage;
import com.rongshu.widget.BanyanDialog;
import com.utils.LogUtil;
import com.utils.SPUtils;
import com.utils.StringUtils;
import com.utils.constants.SPKey;
import com.utils.permissions.OnPermission;
import com.utils.permissions.XXPermissions;
import com.widget.toast.ToastUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import rx.Subscriber;
import rx.functions.Action0;

/**
 * created by zhengweis on 2018/11/19.
 * description：
 */
public class SubmitPostPresenter extends BasePresenter<SubmitPostView> {
    private String[] permissions = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
    private BaseActivity activity;
    private int UPLOAD_PICTURE_SIZE = 1;//为防止内存溢出，每次上传图片数量限制
    private List<String> localPicturesPaths;//需要上传的图片集合
    private List<String> pictureUrlsResponse;//接口返回的图片url集合

    public SubmitPostPresenter(Context context) {
        super(context);
        activity = (BaseActivity) mContext;
        pictureUrlsResponse = new ArrayList<>();
        localPicturesPaths = new ArrayList<>();
    }

    public void postNote(String title, String content, String topImg, int penpalId, String insertImgs) {
        Map<String, Object> map = new HashMap<>();
        map.put("user_id", UserInfoUtils.getUserId());
        map.put("penpalwill_id", penpalId);
        SubmitPostBody body = new SubmitPostBody();
        body.setTitle(title);
        body.setContents(StringUtils.toHTMLString(content));
        body.setTopImg(topImg);
        body.setPostPictures(insertImgs);
        RetorfitService.postSelectPenpal(UserInfoUtils.getUserId(), penpalId,
                Common.encryptionSign(map), body)
                .compose(getView().<INetBean>bindToLife()).doOnSubscribe(new Action0() {
            @Override
            public void call() {

            }
        }).subscribe(new Subscriber<INetBean>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                activity.showLoading(false);
            }

            @Override
            public void onNext(INetBean object) {
                ToastUtils.show(object.getErrMsg());
                if (object.getErrCode() == 0) {
                    getView().submitPostSuccess();
                } else {
                    activity.showLoading(false);
                }
            }
        });
    }

    public void getPicture(final int requestCode, final int maxSelect) {
        if (!XXPermissions.isHasPermission(mContext, permissions)) {
            XXPermissions.with((Activity) mContext).permission(permissions).request(new OnPermission() {
                @Override
                public void hasPermission(List<String> granted, boolean isAll) {
                    toGallery(requestCode, maxSelect);
                }

                @Override
                public void noPermission(List<String> denied, boolean quick) {
                    XXPermissions.gotoPermissionSettings(mContext);
                }
            });
        } else {
            toGallery(requestCode, maxSelect);
        }

    }

    private void toGallery(int requestCode, int maxSelect) {
        PictureSelector.create((Activity) mContext)
                .openGallery(PictureMimeType.ofImage())
                .selectionMode(PictureConfig.MULTIPLE)
                .maxSelectNum(maxSelect)
                .isCamera(true)
                .compress(true)
                .forResult(requestCode);
    }


    /**
     * 处理图片
     *
     * @param pictures
     */
    public void pictureDealWith(List<String> pictures) {
        localPicturesPaths.addAll(pictures);
        subPictures(localPicturesPaths);
    }

    /**
     * 图片分割
     *
     * @param pictures
     */
    public void subPictures(List<String> pictures) {
        if (pictures.size() > UPLOAD_PICTURE_SIZE) {
            List<String> subList = pictures.subList(0, UPLOAD_PICTURE_SIZE);
            uploadPictures(subList);
        } else {
            uploadPictures(pictures);
        }
    }

    /**
     * 图片上传
     *
     * @param subList
     */
    public void uploadPictures(final List<String> subList) {
        Map<String, RequestBody> files = new HashMap<>();
        for (int i = 0; i < subList.size(); i++) {
            File file = new File(subList.get(i));
            files.put("file" + i + "\"; filename=\"" + file.getName(), RequestBody.create(MediaType.parse("image/png"), file));
        }
        FileUploadService.uploadMoreFile(files)
                .compose(getView().<UpLoadImage>bindToLife())
                .subscribe(new Subscriber<UpLoadImage>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        activity.showLoading(false);
                    }

                    @Override
                    public void onNext(UpLoadImage upLoadImage) {
                        if (upLoadImage.getErrCode() == 0) {
                            LogUtil.d("上传的集合：" + subList.toString());
                            List<String> imgUrl = upLoadImage.getResponse().getImgUrl();
                            pictureUrlsResponse.addAll(imgUrl);
                            //移除上传后的图片地址集合
                            localPicturesPaths.removeAll(subList);
                            if (localPicturesPaths.size() > 0) {
                                //移除上传后的图片地址集合，如果集合长度还大于限定长度，再进行分割
                                subPictures(localPicturesPaths);
                            } else {
                                getView().uploadPictureSuccess(pictureUrlsResponse);
                                pictureUrlsResponse.clear();
                            }
                        } else {
                            activity.showLoading(false);
                            ToastUtils.show(upLoadImage.getErrMsg());
                        }
                    }
                });
    }

    public void showHintDialog(final String title, final String content) {
        BanyanDialog.Builder builder = new BanyanDialog.Builder(mContext);
        builder.setTitle("将此次编辑保留");
        builder.setContent("若不保留，将彻底删除");
        builder.setLeft("不保留");
        builder.setRight("保留");
        final BanyanDialog dialog = builder.create();
        builder.setDialogOnClick(new BanyanDialog.Builder.onClickListener() {
            @Override
            public void leftClickListener() {
                SPUtils.putPreferences(SPKey.POST_DRAFT_TITLE, "");
                SPUtils.putPreferences(SPKey.POST_DRAFT_CONTENT, "");
                getView().finishActivity();
                dialog.dismiss();
            }

            @Override
            public void rightClickListener() {
                SPUtils.putPreferences(SPKey.POST_DRAFT_TITLE, title);
                SPUtils.putPreferences(SPKey.POST_DRAFT_CONTENT, content);
                getView().finishActivity();
                dialog.dismiss();
            }
        });
        dialog.show();
    }
}
